#!/usr/bin/env node

const { execSync } = require('child_process');
const fs = require('fs');
const path = require('path');

// 颜色输出
const colors = {
  red: '\x1b[31m',
  green: '\x1b[32m',
  yellow: '\x1b[33m',
  blue: '\x1b[34m',
  magenta: '\x1b[35m',
  cyan: '\x1b[36m',
  white: '\x1b[37m',
  reset: '\x1b[0m'
};

function log(message, color = 'white') {
  console.log(`${colors[color]}${message}${colors.reset}`);
}

function execCommand(command, options = {}) {
  try {
    log(`执行命令: ${command}`, 'cyan');
    const result = execSync(command, { 
      stdio: 'inherit', 
      encoding: 'utf8',
      ...options 
    });
    return result;
  } catch (error) {
    log(`命令执行失败: ${error.message}`, 'red');
    process.exit(1);
  }
}

function checkFileExists(filePath) {
  return fs.existsSync(filePath);
}

function getFileSize(filePath) {
  if (!checkFileExists(filePath)) return 0;
  const stats = fs.statSync(filePath);
  return stats.size;
}

function formatBytes(bytes) {
  if (bytes === 0) return '0 Bytes';
  const k = 1024;
  const sizes = ['Bytes', 'KB', 'MB', 'GB'];
  const i = Math.floor(Math.log(bytes) / Math.log(k));
  return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
}

function analyzeBuild() {
  const distPath = path.join(__dirname, '../dist/h5');
  
  if (!checkFileExists(distPath)) {
    log('构建目录不存在', 'red');
    return;
  }
  
  log('\n=== 构建分析 ===', 'magenta');
  
  // 分析主要文件
  const mainFiles = [
    'index.html',
    'assets/js/app.js',
    'assets/css/app.css'
  ];
  
  mainFiles.forEach(file => {
    const filePath = path.join(distPath, file);
    if (checkFileExists(filePath)) {
      const size = getFileSize(filePath);
      log(`${file}: ${formatBytes(size)}`, 'green');
    }
  });
  
  // 分析 assets 目录
  const assetsPath = path.join(distPath, 'assets');
  if (checkFileExists(assetsPath)) {
    const assets = fs.readdirSync(assetsPath);
    log(`\nAssets 目录包含: ${assets.join(', ')}`, 'blue');
    
    assets.forEach(asset => {
      const assetPath = path.join(assetsPath, asset);
      if (fs.statSync(assetPath).isDirectory()) {
        const files = fs.readdirSync(assetPath);
        log(`  ${asset}/: ${files.length} 个文件`, 'yellow');
      }
    });
  }
  
  // 检查 hash 文件
  const jsFiles = fs.readdirSync(path.join(distPath, 'assets/js')).filter(f => f.endsWith('.js'));
  const cssFiles = fs.readdirSync(path.join(distPath, 'assets/css')).filter(f => f.endsWith('.css'));
  
  const hasHash = jsFiles.some(f => f.includes('.')) && cssFiles.some(f => f.includes('.'));
  
  if (hasHash) {
    log('\n✅ 文件 hash 配置正确', 'green');
  } else {
    log('\n❌ 文件 hash 配置可能有问题', 'red');
  }
}

function main() {
  const args = process.argv.slice(2);
  const isProduction = args.includes('--prod');
  const isAnalyze = args.includes('--analyze');
  
  log('🚀 开始构建 H5 应用...', 'magenta');
  
  // 清理旧的构建文件
  log('\n1. 清理旧的构建文件...', 'yellow');
  execCommand('npm run clean');
  
  // 类型检查
  log('\n2. 执行类型检查...', 'yellow');
  execCommand('npm run typecheck');
  
  // 构建
  log('\n3. 开始构建...', 'yellow');
  const buildCommand = isProduction ? 'npm run build:h5:prod' : 'npm run build:h5';
  execCommand(buildCommand);
  
  // 分析构建结果
  log('\n4. 分析构建结果...', 'yellow');
  analyzeBuild();
  
  // 如果需要分析，生成分析报告
  if (isAnalyze) {
    log('\n5. 生成构建分析报告...', 'yellow');
    execCommand('npm run build:h5:analyze');
  }
  
  log('\n✅ 构建完成！', 'green');
  log('构建文件位置: ./dist/h5', 'cyan');
  
  if (isProduction) {
    log('\n📦 生产环境构建完成，可以部署了！', 'green');
  }
}

// 错误处理
process.on('uncaughtException', (error) => {
  log(`\n❌ 构建过程中发生错误: ${error.message}`, 'red');
  process.exit(1);
});

process.on('unhandledRejection', (reason, promise) => {
  log(`\n❌ 未处理的 Promise 拒绝: ${reason}`, 'red');
  process.exit(1);
});

main();
